package com.markrfield.iRacingTelemetryView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class IRacingTelemetryViewerActivity extends Activity implements OnClickListener {
	
	public static TextView test;
	public static TextView serverStatus;
	private EditText portNumber;
	public static String port;
	
	StreamDataTask task = null;
	private Button startDataButton;
		
	private Thread fst;
	
	private boolean serverThreadRunning = false;
	
	private Intent i;
	private Intent backgroundService;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        backgroundService = new Intent(this, BackgroundService.class);
        
        
        
        
        
        /* Check if it's first run, if it is, start tutorial and setup */
        SharedPreferences settings = getPreferences(MODE_PRIVATE);
        /* If it's the first run */
        /*
        if(!settings.contains("firstRun")) {
        	
        	Intent tutorial = new Intent(this, Tutorial1.class);
        	
        	startActivity(tutorial);
        	
        	SharedPreferences.Editor editor = settings.edit();
        	
        	editor.putString("firstRun", "false");
        	
        	editor.commit();
        	
        }
        */
                
        serverStatus = (TextView)findViewById(R.id.server_status);
        test = (TextView)findViewById(R.id.test);
                
        View startDataOnClick = findViewById(R.id.startDataButton);
        startDataOnClick.setOnClickListener(this);
        
        startDataButton = (Button)findViewById(R.id.startDataButton);
        
        portNumber = (EditText)findViewById(R.id.portNumber);
        
        //fst = new Thread(new ServerThread());
        //task = new StreamDataTask();
                
        
    }

	public void onClick(View v) {
		
		switch(v.getId()) {
		
			case R.id.startDataButton:
							
					
				// If serverThreadRunning == true, stop the thread and set the button to start.
				if(serverThreadRunning) {
					
					// Set it to false
					serverThreadRunning = false;
					
					// Stop the thread
					//task.cancel(true);
					this.stopService(backgroundService);
					
					// Set the text of the button to Start
					startDataButton.setText("Start");
					
				}
				// If serverThreadRunning == false, start the thread and set the button text to stop.
				else {
					
					// Get the entered port number
					port = portNumber.getText().toString();
					
					// Check if the prot number is empty
					if(port.equals("") || port == null) {
						
						// Create an alert dialog, and inform the user that they need to enter a port number.
						AlertDialog alertDialog = new AlertDialog.Builder(this).create();
												
						alertDialog.setMessage("Please enter a port number");
						
						alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								
								dialog.cancel();
								
							}
						});
						
						alertDialog.show();
						
						serverStatus.setText("Disconnected");
						
					}
					// Port number was entered
					else {
						
						// Set serverThreadRunning to true
						serverThreadRunning = true;
				        
						//task.execute();
						this.startService(backgroundService);
				        
				        // Set the button text to Stop.
				        startDataButton.setText("Stop");
						
					}
					
				}
						
				break;
		
		}
		
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		MenuInflater inflater = getMenuInflater();
		
		inflater.inflate(R.menu.menu, menu);
		
		return super.onCreateOptionsMenu(menu);
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()) {
		
			case R.id.optionsMenu:
				Intent options = new Intent(this, Options.class);
				startActivity(options);
				break;
		
		}
		
		return super.onOptionsItemSelected(item);
		
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		
		super.onStop();
		
				
	}
	
	private class StreamDataTask extends AsyncTask<String, Void, String> {
		
		public ServerSocket ss = null;

		@Override
		protected String doInBackground(String... params) {
			
			// ServerSocket
			//ServerSocket ss = null;
			
			try {
				// Create new ServerSocket, listening on specified port
				ss = new ServerSocket(8081);
							
				while(true) {
					// Accept a new client
					Socket s = ss.accept();
					
					// Create a new buffered reader
					BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
					
					// Read line
					//System.out.println(br.readLine());
					
					// Close BufferedReader and Socket.
					br.close();
					s.close();
					
				}
				
				
			} catch (IOException e) {
				e.printStackTrace();
				Log.w("iRacing", "Error");
			}
						
			return null;
		}
		
	}
    
}